import requests
from bs4 import BeautifulSoup

# WxPusher配置
app_token = "AT_UveVJD7qGF07XJqnA9Hv7sDqzZ5iUJHM"
uid = "UID_FBRva0GBC50cnH4Q3NtKUaKM8kQI"
api_url = "https://wxpusher.zjiecode.com/api/send/message/"


def get_baidu_title():
    try:
        # 访问百度首页
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get('https://www.baidu.com', headers=headers)
        response.raise_for_status()

        # 解析标题
        soup = BeautifulSoup(response.text, 'html.parser')
        title = soup.title.string if soup.title else "未找到标题"
        return title
    except Exception as e:
        return f"获取百度标题失败: {str(e)}"


def send_wxpusher_message(content):
    params = {
        "appToken": app_token,
        "content": content,
        "uid": uid,
        "url": "https://wxpusher.zjiecode.com"
    }
    try:
        response = requests.get(api_url, params=params)
        response.raise_for_status()
        return response.json()
    except Exception as e:
        return {"success": False, "msg": str(e)}


if __name__ == "__main__":
    # 获取百度标题
    baidu_title = get_baidu_title()
    print(f"百度标题: {baidu_title}")

    # 推送消息
    result = send_wxpusher_message(f"百度首页标题: {baidu_title}")
    if result.get("success"):
        print("消息推送成功！")
    else:
        print(f"消息推送失败: {result.get('msg')}")